import { caller } from '../caller'

/**
 * 获取第三方平台ComponentAccessToken
 * @param component_appid
 * @param component_appsecret
 * @param component_verify_ticket
 */
export async function getComponentAccessToken(
    component_appid: string,
    component_appsecret: string,
    component_verify_ticket: string,
) {
    return caller
        .request<{
            component_access_token: string
            expires_in: number
        }>({
            method: 'POST',
            url: '/cgi-bin/component/api_component_token',
            data: {
                component_appid,
                component_appsecret,
                component_verify_ticket,
            },
        })
        .then((resp) => resp.data)
}

/**
 * 获取第三方平台预授权码
 * @param component_appid
 * @param component_access_token
 * @returns
 */
export async function getPreAuthCode(component_appid: string, component_access_token: string) {
    return caller
        .request<{
            pre_auth_code: string
            expires_in: number
        }>({
            method: 'POST',
            url: '/cgi-bin/component/api_create_preauthcode',
            params: {
                component_access_token,
            },
            data: {
                component_appid,
            },
        })
        .then((resp) => resp.data)
}

export interface AuthorizationInfo {
    authorizer_appid: string
    authorizer_access_token: string
    expires_in: number
    authorizer_refresh_token: string
    func_info: {
        funcscope_category: {
            id: number
        }
    }[]
}

/**
 * 查询授权信息
 */
export async function queryAuth(component_appid: string, component_access_token: string, authorization_code: string) {
    return caller
        .request<{
            authorization_info: AuthorizationInfo
        }>({
            method: 'POST',
            url: '/cgi-bin/component/api_query_auth',
            params: {
                component_access_token,
            },
            data: {
                component_appid,
                authorization_code,
            },
        })
        .then((resp) => resp.data)
}

export async function refreshAuthorizerAccessToken(
    component_appid: string,
    component_access_token: string,
    authorizer_appid: string,
    authorizer_refresh_token: string,
) {
    return caller
        .request<{
            authorizer_access_token: string
            expires_in: number
            authorizer_refresh_token: string
        }>({
            method: 'POST',
            url: '/cgi-bin/component/api_authorizer_token',
            params: {
                component_access_token,
            },
            data: {
                component_appid,
                authorizer_appid,
                authorizer_refresh_token,
            },
        })
        .then((resp) => resp.data)
}
